<?php
/**
 * 健康营养食谱小程序后端API入口
 * 支持高血糖、高尿酸人群的饮食管理
 */

// 设置响应头
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// 自动加载类文件
spl_autoload_register(function($className) {
    $classFile = __DIR__ . '/classes/' . $className . '.php';
    if (file_exists($classFile)) {
        require_once $classFile;
    }
});

// 加载配置文件
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/config.php';

// 路由处理
$requestUri = $_SERVER['REQUEST_URI'];
$path = parse_url($requestUri, PHP_URL_PATH);
$path = str_replace('/api', '', $path);

// 获取请求方法
$method = $_SERVER['REQUEST_METHOD'];

// 获取请求数据
$input = file_get_contents('php://input');
$data = json_decode($input, true) ?: [];

// 合并GET和POST数据
if ($method === 'GET') {
    $data = array_merge($data, $_GET);
} elseif ($method === 'POST') {
    $data = array_merge($data, $_POST);
}

// 路由分发
try {
    $router = new Router();
    $response = $router->handle($path, $method, $data);
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'code' => 500,
        'message' => '服务器内部错误',
        'error' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}

?>